import datetime
import random


class TimeFormatTransform(object):

    def timestamp_to_time(self, timestamp):
        """
        :param timestamp: 时间戳
        :return: 将时间戳转换成时间格式
        """
        return datetime.datetime.fromtimestamp(timestamp / 1000)

    def get_random_date(self, start_date, end_date):
        """
        :param start_date: 开始日期
        :param end_date: 结束日期
        :return: 开始日期至结束日期的任意一天的时间（不包含结束日期）
        """
        start = datetime.datetime.strptime(start_date, "%Y-%m-%d")
        end = datetime.datetime.strptime(end_date, "%Y-%m-%d")
        delta = end - start
        total_seconds = delta.days * 24 * 3600 + delta.seconds
        random_seconds = random.randint(0, total_seconds)
        return start + datetime.timedelta(seconds=random_seconds)

    def get_random_date_str(self, start_date, end_date):
        """
        :param start_date: 开始日期
        :param end_date: 结束日期
        :return: 开始日期至结束日期的任意一天的时间（不包含结束日期）(str类型数据)
        """
        start = datetime.datetime.strptime(start_date, "%Y-%m-%d")
        end = datetime.datetime.strptime(end_date, "%Y-%m-%d")
        delta = end - start
        total_seconds = delta.days * 24 * 3600 + delta.seconds
        random_seconds = random.randint(0, total_seconds)
        return datetime.datetime.strftime(start + datetime.timedelta(seconds=random_seconds), "%Y-%m-%d %H:%M:%S")

    def random_time_in_range(self, date_str, start_hour=9, end_hour=17):
        base_date = datetime.datetime.strptime(date_str, '%Y-%m-%d')

        # 设置开始和结束时间
        start_time = base_date.replace(hour=start_hour, minute=0, second=0)
        end_time = base_date.replace(hour=end_hour, minute=0, second=0)
        delta = (end_time - start_time).seconds
        random_seconds = random.randint(0, delta)
        return start_time + datetime.timedelta(seconds=random_seconds)


if __name__ == '__main__':
    print(TimeFormatTransform().random_time_in_range('2025-10-09', 9, 17))  # 输出9:00-17:00之间的随机时间
